import request from '@/utils/request';
import type { BasicMsg, BasicMsgWithData, User, LoginRequest, RegisterRequest } from '@/types';

// 用户登录（通过用户名查询用户）
export const login = (data: LoginRequest): Promise<BasicMsgWithData<User[]>> => {
  return request({
    url: `/api/users/username/${data.username}`,
    method: 'get'
  });
};

// 验证用户密码（调用后端专门的密码验证接口）
export const verifyUserPassword = async (username: string, password: string): Promise<BasicMsg> => {
  try {
    // 调用后端的密码验证接口
    const response: any = await request({
      url: '/api/users/verify-password',
      method: 'post',
      data: {
        username: username,
        password: password
      }
    });
    
    
    return {
      operateResult: response.operateResult || 'UNSUSS',
      errorMsg: response.errorMsg || '验证失败',
      errorCode: response.errorCode || 'VERIFY_ERROR'
    };
    
  } catch (error: any) {
    return { 
      operateResult: 'UNSUSS' as const, 
      errorMsg: error.message || '验证失败', 
      errorCode: 'API_ERROR' 
    };
  }
};

// 用户注册
export const register = (data: RegisterRequest): Promise<BasicMsg> => {
  return request({
    url: '/api/users',
    method: 'post',
    data: {
      username: data.username,
      password: data.password,
      nickname: data.nickname,
      email: data.email || '',
      phonenumber: data.phonenumber || '',
      sex: data.sex || '2',
      userType: data.userType || '1' // 使用用户选择的角色
    }
  });
};

// 获取所有用户
export const getAllUsers = (): Promise<BasicMsgWithData<User[]>> => {
  return request({
    url: '/api/users',
    method: 'get'
  });
};

// 根据ID获取用户
export const getUserById = (id: number): Promise<BasicMsgWithData<User>> => {
  return request({
    url: `/api/users/${id}`,
    method: 'get'
  });
};

// 创建用户
export const createUser = (data: User): Promise<BasicMsg> => {
  return request({
    url: '/api/users',
    method: 'post',
    data
  });
};

// 更新用户
export const updateUser = (id: number, data: User): Promise<BasicMsg> => {
  return request({
    url: `/api/users/${id}`,
    method: 'put',
    data
  });
};

// 删除用户
export const deleteUser = (id: number): Promise<BasicMsg> => {
  return request({
    url: `/api/users/${id}`,
    method: 'delete'
  });
};

// 根据用户类型查询
export const getUsersByType = (userType: string): Promise<BasicMsgWithData<User[]>> => {
  return request({
    url: `/api/users/type/${userType}`,
    method: 'get'
  });
};

// 验证密码（基于本地存储的密码验证）
export const verifyPassword = (username: string, password: string): Promise<BasicMsg> => {
  return new Promise((resolve, reject) => {
    // 从localStorage获取存储的密码信息
    const storedPassword = localStorage.getItem(`password_${username}`);
    
    if (storedPassword) {
      // 如果本地存储了密码，直接比较
      if (storedPassword === password) {
        resolve({ operateResult: 'SUCC' as const, errorMsg: '', errorCode: '' });
      } else {
        reject({ message: '旧密码错误' });
      }
    } else {
      // 如果没有存储密码，则通过后端查询用户来验证
      request({
        url: `/api/users/username/${username}`,
        method: 'get'
      }).then((res: any) => {
        if (res.operateResult === 'SUCC' && res.data && res.data.length > 0) {
          const user = res.data[0];
          // 直接比较数据库中的密码
          if (user.password === password) {
            // 验证通过，存储密码供下次使用
            localStorage.setItem(`password_${username}`, password);
            resolve({ operateResult: 'SUCC' as const, errorMsg: '', errorCode: '' });
          } else {
            reject({ message: '旧密码错误' });
          }
        } else {
          reject({ message: '用户不存在' });
        }
      }).catch(() => {
        reject({ message: '验证失败' });
      });
    }
  });
};

// 修改密码（不验证旧密码，因为调用者已经验证过了）
export const changePassword = (id: number, _oldPassword: string, newPassword: string): Promise<BasicMsg> => {
  return getUserById(id).then(res => {
    if (res.operateResult === 'SUCC' && res.data) {
      // 直接更新密码（旧密码已经在调用前验证过了）
      const userData = { ...res.data, password: newPassword };
      return updateUser(id, userData as any).then(updateRes => {
        // 更新成功后，更新本地存储的密码
        if (res.data && res.data.username) {
          localStorage.setItem(`password_${res.data.username}`, newPassword);
        }
        return updateRes;
      });
    }
    return Promise.reject({ message: '用户不存在' });
  });
};

